package com.sims.util;

import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;
import com.sims.action.StudentPosition.ModifyStudentPositionAction;
import com.sims.action.general.LoginAction;
import com.sims.action.student.*;
import com.sims.action.teacher.*;
import com.sims.action.manager.*;

@SuppressWarnings("serial")
public class CheckAuthorityInterceptor extends AbstractInterceptor {
	
	private final static Set<Class> unInterceptActions = new HashSet<Class>(Arrays.asList(new Class[]{
			LoginAction.class,
			StudentLoginAction.class,
			TeacherLoginAction.class,
			ManageLoginAction.class
	}));
	
	private final static Set<Class> onlyStudentActions = new HashSet<Class>(Arrays.asList(new Class[]{
			ModifyStudentBasicInfoAction.class,
			ModifyStudentPasswordAction.class,
			ModifyTelAction.class
	}));
	
	private final static Set<Class> onlyTeacherActions = new HashSet<Class>(Arrays.asList(new Class[]{
			ModifyStudentPositionAction.class,
			ModifyTeacherBasicInfoAction.class,
			ModifyTeacherPasswordAction.class,
			
	}));
	
	private final static Set<Class> onlyManagerActions = new HashSet<Class>(Arrays.asList(new Class[]{
			addStudentAction.class,
			AddTeacherAction.class,
			FindStudentAction.class,
			FindTeacherAction.class,
			ModifyManagePasswordAction.class,
			ModifyStudentAction.class,
			ModifyTeacherAction.class
	}));
	
	@Override
	public void init() {
		super.init();
	}
	@Override
	public String intercept(ActionInvocation arg0) throws Exception {
		if (unInterceptActions.contains(arg0.getAction().getClass()))
			return arg0.invoke();
		
		Map<String, String> result = new HashMap<String, String>();
		
		if (!HttpSessionUtil.isLogin()) {
			result.put(Constant.ERROR, "登陆超时，请重新登录");
			((ActionEnhanced)arg0.getAction()).setResult(result);
			return Action.ERROR;
		}
		
		if (HttpSessionUtil.getUserType() != Constant.STUDENT) {
			if (onlyStudentActions.contains(arg0.getAction().getClass())) {
				result.put(Constant.ERROR, "抱歉，你没有权限执行本次操作");
				((ActionEnhanced)arg0.getAction()).setResult(result);
				return Action.ERROR;
			}
		}
		if (HttpSessionUtil.getUserType() != Constant.TEACHER) {
			if (onlyTeacherActions.contains(arg0.getAction().getClass())) {
				result.put(Constant.ERROR, "抱歉，你没有权限执行本次操作");
				((ActionEnhanced)arg0.getAction()).setResult(result);
				return Action.ERROR;
			}
		}
		if (HttpSessionUtil.getUserType() != Constant.MANAGER) {
			if (onlyManagerActions.contains(arg0.getAction().getClass())) {
				result.put(Constant.ERROR, "抱歉，你没有权限执行本次操作");
				((ActionEnhanced)arg0.getAction()).setResult(result);
				return Action.ERROR;
			}
		}
		return arg0.invoke();
	}

}
